import React, { PureComponent } from "react";
import { getSmsCCC, getSmsCode, register } from "../../services/api"; // net

import md5code, { dateStr, md5 } from "@Utils/md5.js"; // salt
import { clientType, changeURLArg } from "@Utils"; // salt

import { Toast, Mask } from "antd-mobile";

import ContextApp from "@Pages/context";

import "./Login.scss";

export default class Login extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      phoneNum: "",
      codeNum: "",
      countDown: 60,
      isPhoneFocus: false,
      isPasswordFocus: false,
    };
  }
  

  componentDidMount() {
    // 获取验证码前所需的盐巴 不主动获取 又父组件调用
    // this.getSmsCCC();
  }

  async getSmsCCC() {
    // debugger;
    if (!this.context.openId) return;
    const param = {
      code: md5code,
      openId: this.context.openId,
    };
    let { code, data } = await getSmsCCC(param);
    if (code == 200) {
      this.state.saltcode = data;
    }

    console.log(this.state);
  }

  // 获取短信验证码
  async getSmsCode() {
    const { phoneNum } = this.state;
    if (!this.checkPhoneNum(phoneNum)) return;

    if (phoneNum) {
      let params = {
        phone: phoneNum,
        openId: this.context.openId,
        index: md5(dateStr + "-" + this.state.saltcode),
      };

      await getSmsCode(params).then((res) => {
        if (res.data && res.data.codeIndex) {
          this.state.codeIndex = res.data.codeIndex;
          this.setState({
            countDownShow: true,
          });
          this.countDownStar();
          Toast.show({
            content: "发送成功",
          });
        } else {
          Toast.show({
            content: res.message,
          });
        }
      });
    }
  }

  async goRegister() {
    let params = {
      phone: this.state.phoneNum,
      codeIndex: this.state.codeIndex,
      code: this.state.codeNum,
      openId: this.context.openId,
      clientType: clientType(),
      // deviceCode: "OGB90062002270131",
      oid: 108,
    };
    let { code, data, msg = "" } = await register(params);
    if (code == 200) {
      window.location.href = changeURLArg(
        window.location.href,
        "phone",
        data.phone
      );
      // window.location.reload();
      // this.props.ctrlMask();
    } else {
      Toast.show({
        content: msg,
      });
    }
  }

  render() {
    let {
      phoneNum,
      codeNum,
      countDownShow,
      countDown,
      isPhoneFocus,
      isPasswordFocus,
    } = this.state;
    return (
      <Mask visible={this.context.isShowLogin}>
        {/* className="maskContent" style={{ top: "25%" }} */}
        <div style={{ marginTop: "35%" }}>
          <div className="register-box">
            <h3 style={{ marginBottom: "25px" }}>用户登录</h3>
            <div
              className={`register-codeBox ${isPhoneFocus ? "onfocus" : ""}`}
            >
              <input
                className="register-phone"
                maxLength={11}
                value={phoneNum}
                onChange={this.phoneInput.bind(this)}
                placeholder="请输入手机号"
              ></input>
              <div className={`icon_input icon_input_phoneNum`}></div>
              {phoneNum.length >= 1 ? (
                <div
                  className="icon_clearPhoneNum"
                  // 清空电话号码
                  onClick={() => {
                    this.setState({
                      phoneNum: "",
                    });
                  }}
                ></div>
              ) : null}
            </div>

            <div
              className={`register-codeBox ${isPasswordFocus ? "onfocus" : ""}`}
            >
              <input
                className="register-code"
                maxLength={8}
                value={codeNum}
                onChange={this.codeInput.bind(this)}
                placeholder="请输入验证码"
              ></input>
              <div className="icon_input icon_Input_Password"></div>
              <div className="getCodeBtn">
                {countDownShow ? (
                  <span>({countDown}s)</span>
                ) : (
                  <span onClick={() => this.getSmsCode()}> 获取验证码</span>
                )}
              </div>
            </div>
            <div>
              <button
                className={`register-btn ${
                  phoneNum.length == 11 && codeNum.length >= 3 ? "" : "disabled"
                }`}
                onClick={() => {
                  phoneNum.length == 11 &&
                    codeNum.length >= 3 &&
                    this.goRegister();
                }}
              >
                登录
              </button>
            </div>
          </div>
        </div>
        <div
          className="MaskCloseIcon"
          style={{ marginTop: "33px", position: "relative" }}
          onClick={() => this.props.closeLogin(false)}
        ></div>
      </Mask>
    );
  }

  // 开始倒计时
  countDownStar() {
    const { countDown } = this.state;
    if (countDown > 0) {
      let newCount = countDown - 1;

      this.setState({ countDown: newCount });
    }
    if (countDown <= 0) {
      this.setState({
        countDownShow: false,
      });
    } else {
      setTimeout(
        function () {
          this.countDownStar();
        }.bind(this),
        1000
      );
    }
  }

  // 电话号码改变
  phoneInput(e) {
    //设置数据的值，用this.setState({})
    this.setState({
      phoneNum: e.target.value,
      isPhoneFocus: e.target.value.length > 0,
    });
  }

  // 验证码改变
  codeInput(e) {
    //设置数据的值，用this.setState({})
    this.setState({
      codeNum: e.target.value,
      isPasswordFocus: e.target.value.length > 0,
    });
  }

  // 校验手机号
  checkPhoneNum(phoneNum) {
    let reg = new RegExp(
      "^(13[0-9]|14[579]|15[0-3,5-9]|16[0-9]|17[0135678]|18[0-9]|19[0-9])\\d{8}$"
    );
    let mobile = phoneNum.replace(/\D/g, "");
    if (!mobile.length) {
      Toast.show({
        content: "请输入手机号！",
      });
      return false;
    } else if (!reg.test(mobile)) {
      Toast.show({
        content: "请输入正确手机号！",
      });
      return false;
    } else {
      return true;
    }
  }
}

Login.contextType = ContextApp;
